package va.radiomaria.p2p;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;


import org.jibble.simplewebserver.SimpleWebServer;

import va.radiomaria.gui.DataModel;
import va.radiomaria.gui.LoggerInstance;

import com.google.common.io.Files;

/**
 * Starts a new WebServer one the port 8080 + random int [0-100]
 * @author panfred
 */
public class WebServer {
	
	int port = 8080 + new Random().nextInt(100);
	InetAddress localhost;
	DataModel model = null;
	SimpleWebServer server = null;

	public WebServer(){
		model = DataModel.getInstance();
		startNewWebserver();
	}

    private void startNewWebserver() {
    	try {
			server = new SimpleWebServer(new File("./"), port);
			localhost = InetAddress.getLocalHost();
			model.addConsoleOutput("started webserver at " + localhost.getHostAddress() + " and port " + port, LoggerInstance.MISC);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String addFile(File file, boolean isFirstUpload) throws UnknownHostException, IOException {
		if(server == null) {
			startNewWebserver();
		}
    	String host = localhost.getHostAddress();
    	String fileName = file.getName();
    	if(isFirstUpload){
    		File newFile = new File("." + File.separator + fileName);
    		Files.copy(file, newFile);
            host = "http://" + host + ":" + port; 
            model.addConsoleOutput("added first instance of " + fileName + " at webserver " + localhost.getHostAddress(), LoggerInstance.MISC);
            return host + "/" + file.getName();
    	} else {
            host = "http://" + host + ":" + port; 
            return host + "/" + "Replications/" + fileName;
    	}

    }
    
    public void shutDown() {
    	server = null;
    }
    
    public String getUrlAsString(){
    	return new String("http://" + localhost.getHostAddress() + ":" + port);
    }
}
